package de.osmembrane.source_file_header;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Replaces the header by a given one, for the given file.
 * 
 * @author jakob_jarosch
 */
public class Replacer {

	private File file;
	
	public Replacer(File file) {
		this.file = file;
	}
	
	/**
	 * Replaces the old header with a new one.
	 * 
	 * @param header
	 * @throws IOException
	 */
	public void replace(String header) throws IOException {
		String file = loadFile();
		
		Matcher matcher = Pattern.compile("package ([a-zA-Z0-9\\._-]+);").matcher(file);
		int firstChar = matcher.start();
		
		String prefix;
		if(firstChar > 0) {
			prefix = file.substring(0, firstChar);
		} else {
			prefix = "";
		}
		String sufix = file.substring(firstChar);
		
		/* try to remove exisiting comments from prefix */
		Matcher prefixMatcher = Pattern.compile("\\/\\*(.*?)\\*\\/", Pattern.MULTILINE | Pattern.DOTALL).matcher(prefix);
		prefix = prefixMatcher.replaceAll("");
		
		/* replace too mutch line breaks */
		Matcher prefixMatcher2 = Pattern.compile("\n\n", Pattern.MULTILINE | Pattern.DOTALL).matcher(prefix);
		prefix = prefixMatcher2.replaceAll("\n");
		
		file = header + prefix + sufix;
		
		saveFile(file);
	}
	
	/**
	 * Load the file.
	 * 
	 * @return
	 * @throws IOException
	 */
	private String loadFile() throws IOException {
		BufferedReader in = new BufferedReader(new FileReader(file));
		String line;
		StringBuilder builder = new StringBuilder();
		while((line = in.readLine()) != null) {
			builder.append(line + "\n");
		}
		in.close();
		
		return builder.toString();
	}
	
	/**
	 * Save the file.
	 * 
	 * @param file
	 * @throws IOException
	 */
	private void saveFile(String file) throws IOException {
		BufferedWriter out = new BufferedWriter(new FileWriter(this.file));
		out.append(file);
		out.close();
	}
}
